package tool

import (
	"errors"
	p "fhst/templates"
	"fhst/utils"
	"fmt"
	"strings"

	log "github.com/sirupsen/logrus"
	"github.com/spf13/viper"
)

func AddMeiliSearch() error {
	defer func() {
		info := utils.History{
			Name:   "Meilisearch",
			Op:     "开启搜索引擎模式",
			Common: "fhst tool meilisearch",
		}
		_, err := utils.AddHistory(&info)
		if err != nil {
			log.Error(err)
		}
	}()

	// 数据库初始化
	utils.ConnectInit()

	// 判断当前位置是否有utils文件夹
	if !utils.IsPathExists(".fhst") {
		return errors.New("未发现.fhst文件，请回到项目根目录")
	}

	if utils.IsPathExists("core/admin/templates/search") {
		return errors.New("core/admin文件夹已存在")
	}

	log.Infof("初始化core/admin/templates/search目录")
	// 创建核心文件夹
	_, err := utils.ExecCommandString("mkdir -p core/admin/templates/search")
	if err != nil {
		return err
	}

	rs, err := utils.ReadFile(".fhst")
	if err != nil {
		return err
	}

	pkgname := strings.Split(string(rs), ":")
	data := map[string]interface{}{
		"Pkg":         pkgname[1],
		"ProjectName": pkgname[0],
		"Log":         viper.GetBool("log.enable"),
		"Admin":       viper.GetBool("admin"),
		"Apps":        viper.GetStringSlice("app"),
		"Jwt":         viper.GetBool("jwt"),
		"Swagger":     viper.GetBool("swagger"),
		"Meili":       viper.GetBool("meili.enable"),
	}

	// 写入配置文件
	defer func() {
		viper.Set("meili.enable", false)
		viper.WriteConfigAs(fmt.Sprintf("%s.yaml", pkgname[0]))
	}()

	log.Infof("初始化search.tmpl")
	err = utils.WriteFileByTemplate(p.Tool, "tool/search.tmpl", "utils/search.go", nil)
	if err != nil {
		return err
	}

	log.Infof("初始化search.html")
	err = utils.WriteFileByTemplate(p.Views, "views/admin/search/search.html", "core/admin/templates/search/search.html", nil)
	if err != nil {
		return err
	}

	log.Infof("更新化 controller.go")
	err = utils.WriteFileByTemplate(p.Views, "views/core/controller.tmpl", "core/admin/controller.go", data)
	if err != nil {
		return err
	}

	return nil
}
